package com.sjsu.aws.simplocks;

import java.util.Map;

/**
 * 
 * @author Shweta Dattatreya
 * 
 */
public class AWSClientWatchdog extends Thread {

	AWSClient client;
	long interval;

	public AWSClientWatchdog(AWSClient c, long intvl) {
		client = c;
		interval = intvl;
	}

	/**
	 * 
	 * @throws Exception
	 */
	public void purgeTimedoutItems() throws Exception {
		synchronized (client) {
			Map<String, String> items;
			items = client.queryTable();
			for (String key : items.keySet()) {
				long now = System.currentTimeMillis();
				long expiry = Long.valueOf(items.get(key));
				if (now > expiry) {
					System.out.println("Killing the Leader after time out : ");
					client.deleteItem(key);
				}
			}
		}
	}

	public void run() {
		while (true) {
			try {
				Thread.sleep(interval);
				purgeTimedoutItems();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
